package zpx.web;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.net.ftp.FTPClient;
import org.compass.core.util.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import zpx.iservice.IFtpAttachmentService;
import zpx.iservice.IUserService;
import zpx.model.FtpAttachment;
import zpx.model.User;
import zpx.model.fileUploadStatus;
import zpx.util.UploadFile;
import zpx.util.myProgressListener;


@Controller
@RequestMapping("/ftpUpload")
public class ftpUpoadController {
	
		private IFtpAttachmentService ftpAttachmentService;
	
		public IFtpAttachmentService getFtpAttachmentService() {
			return ftpAttachmentService;
		}

		@Resource
		public void setFtpAttachmentService(IFtpAttachmentService ftpAttachmentService) {
			this.ftpAttachmentService = ftpAttachmentService;
		}
		
		private IUserService userService;
		
		public IUserService getUserService() {
			return userService;
		}
		
		@Resource
		public void setUserService(IUserService userService) {
			this.userService = userService;
		}
		
			
	/**
	 * 上传视频
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
		@RequestMapping("/upload")
		public String  uploadstar(HttpServletRequest request,
				HttpServletResponse response) throws IOException{
		  response.setCharacterEncoding("utf-8");
		/*  if(SystemContext.ftp==null){
			  SystemContext.ftp=new FTPClient();
			  System.out.println("0");
		  }else{
			  if(SystemContext.ftp.isConnected()){
				  SystemContext.input.close();
				  SystemContext.outputstream.flush();
				  SystemContext.outputstream.close();
				  SystemContext.ftp.disconnect();				  
				  SystemContext.ftp.logout();
				  return null;
			  }
			  SystemContext.ftp=new FTPClient();
			  
			  System.out.println("1");
		  }*/
		  User loginUser = (User)request.getSession().getAttribute("loginUser");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(2048*1024);
			myProgressListener getBarListener = new myProgressListener(request);
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				List formList = upload.parseRequest(request);
				Iterator<Object> formItem = formList.iterator();
				while (formItem.hasNext()) {
					FileItem item = (FileItem) formItem.next();
					if (item.isFormField()) {
						System.out.println("Field Name:" + item.getFieldName());
					} else {
						InputStream input=null; 
						String fileName = item.getName().substring(item.getName().lastIndexOf("\\")+1);
						input = item.getInputStream();
						UploadFile ftpUploadFile = new UploadFile();
						ftpUploadFile.UploadFile(input,fileName,getBarListener,loginUser);	
					}
				}
			} catch (FileUploadException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return null;
		
	}
		/**
		 * 下载视频
		 */
		@RequestMapping("/downFtp")
		public String  downFtp(HttpServletRequest request,
				HttpServletResponse response) throws IOException{
			
			String path=request.getParameter("path");
			System.out.println(path);
			UploadFile ftpUploadFile = new UploadFile();
			String attaId=request.getParameter("attaId");
			FtpAttachment ftpAttachment=ftpAttachmentService.getFtpAttachment(attaId);
			ftpUploadFile.downFile(ftpAttachment.getAttaPath());
			return null;
			
		}
		
		
		/**
		 * 获得文件列表信息
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value="/getFtpList",method = { RequestMethod.GET, RequestMethod.POST })
		@ResponseBody
		public JSONObject getFtpList(HttpServletRequest request, HttpServletResponse response) {
			// ��Ų�ѯ����
	        Map<String, Object> searchMap = new HashMap<String, Object>();
			JSONObject jsonObject = new JSONObject();
	        JSONArray jsonArray = new JSONArray();
	        int total = this.ftpAttachmentService.getFtpCount(searchMap);
	     // ��ʼ��¼��
	        int startIndex = 0;
	        // ÿҳȡ�õ�����
	        int pageSize = 20;
	        // ��ҳ���ȡ������ҳ��
	        String rows = request.getParameter("rows");
	        String page = request.getParameter("page");
	        // �����ҳ��ʾ
	        if (rows != null && !"".equals(rows) && page != null && !"".equals(page)) {
	            int iPage = Integer.parseInt(page);
	            pageSize = Integer.parseInt(rows);
	            startIndex = (iPage - 1) * pageSize;
	            while (startIndex >= total && startIndex > 0) {
	                iPage--;
	                startIndex = (iPage - 1) * pageSize;
	            }
	            searchMap.put("startIndex", startIndex + "");
	            searchMap.put("pageSize", pageSize + "");
	        }
	        List<FtpAttachment> datalist=ftpAttachmentService.getFtpttachmentsLst(searchMap);
	        // ����δnull��ҳ��{}������
	        if (datalist == null) {
	            datalist = new ArrayList<FtpAttachment>();
	        }
	        // ��������
	        if (datalist != null) {
	            for (FtpAttachment ftpAttachment : datalist) {
	                jsonArray.add(this.getFtpAttachmentToJsonObj(ftpAttachment));
	            }
	        }
	        jsonObject.put("rows", jsonArray);
	        jsonObject.put("total", total);
			return jsonObject;
		}
		
    //跳转到上传页面
	@RequestMapping("/goUpload")
	public String goUpload(HttpServletRequest request,
            HttpServletResponse response){
		return "ftp/ftpUpload";
	}
	
	 /**
     * 跳转到文件下载或编辑页面
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/ftpDownOrEdit")
    public ModelAndView ftpDownOrEdit(HttpServletRequest request,
            HttpServletResponse response) {
    	
    	//操作标识(2编辑 3下载)
    	String operWay=request.getParameter("operWay");
    	
    	Map<String, Object> map = new HashMap<String, Object>();
    	String id=request.getParameter("id");
    	FtpAttachment ftpAttachment=new FtpAttachment();  		
        ftpAttachment=ftpAttachmentService.getFtpAttachment(id);	
    	map.put("ftpAttachment", ftpAttachment);
    	map.put("operWay", operWay);
    	//map.put("comAttachments", attaList);
    	if(operWay.equals("3")){
    		return new ModelAndView("ftp/ftpDown",map);
    	}else{
    		return new ModelAndView("ftp/ftpEdit",map);
    	}
        
    }
	
    
	/**
	 * 跳转到文件列表页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/goFtpList")
	public String goFtpList(HttpServletRequest request,
            HttpServletResponse response){
		return "ftp/ftpList";
	}

    /**
     * ftp文件上传
     * 
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> add(HttpServletRequest request, FtpAttachment ftpAttachment,String fileNames,String filePaths,String delComAttIds) {
		/*if(br.hasErrors()) {
			return "user/add";
		}*/
		HttpSession session=request.getSession();
		User loginUser = (User)session.getAttribute("loginUser");
		fileUploadStatus status = (fileUploadStatus) session.getAttribute("status");
		Map<String, Object> searchMap=new HashMap<String, Object>();
		ftpAttachment.setAttaPath(status.getFilepath());
		ftpAttachment.setStatus("0");
		ftpAttachment.setAttaStatus("0");
		searchMap.put("ftpAttachment", ftpAttachment);
		searchMap.put("fileNames", fileNames);
		searchMap.put("filePaths", filePaths);
		searchMap.put("delComAttIds", delComAttIds);
		searchMap.put("loginUser", loginUser);
		ftpAttachmentService.saveOrUpdateFtpAttachment(searchMap);
		Map<String, String> returnMap = new HashMap<String, String>();
        returnMap.put("info", "success");
		return returnMap;
	}

	//类对面转为json
	private JSONObject getFtpAttachmentToJsonObj(FtpAttachment ftpAttachment) {
        JSONObject jsonObj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.hasText(ftpAttachment.getAttaId())){
            jsonObj.put("attaId",ftpAttachment.getAttaId());
        }
        if(StringUtils.hasText(ftpAttachment.getAttaGroupId())){
            jsonObj.put("attaGroupId",ftpAttachment.getAttaGroupId());
        }
        if(StringUtils.hasText(ftpAttachment.getAttaName())){
            jsonObj.put("attaName",ftpAttachment.getAttaName());
        }
        if(StringUtils.hasText(ftpAttachment.getAttaPath())){
            jsonObj.put("attaPath",ftpAttachment.getAttaPath());
        }
        if(StringUtils.hasText(ftpAttachment.getAttaStatus())){
            jsonObj.put("attaStatus",ftpAttachment.getAttaStatus());
        }
        if(StringUtils.hasText(ftpAttachment.getAttaType())){
            jsonObj.put("attaType",ftpAttachment.getAttaType());
        }
        if(StringUtils.hasText(ftpAttachment.getContent())){
            jsonObj.put("content",ftpAttachment.getContent());
        }
        if(ftpAttachment.getCreateDate()!=null){
            jsonObj.put("createDate",dateFormat.format(ftpAttachment.getCreateDate()));
        }
        if(StringUtils.hasText(ftpAttachment.getCreatePerson())){
            jsonObj.put("createPerson",ftpAttachment.getCreatePerson());
        }
        if(StringUtils.hasText(ftpAttachment.getKeywords())){
            jsonObj.put("keywords",ftpAttachment.getKeywords());
        }
        if(StringUtils.hasText(ftpAttachment.getRecordId())){
            jsonObj.put("recordId",ftpAttachment.getRecordId());
        }
        if(StringUtils.hasText(ftpAttachment.getRemark())){
            jsonObj.put("remark",ftpAttachment.getRemark());
        }
        if(ftpAttachment.getUpdateDate()!=null){
            jsonObj.put("updateDate",dateFormat.format(ftpAttachment.getUpdateDate()));
        }
        if(StringUtils.hasText(ftpAttachment.getUpdatePerson())){
            jsonObj.put("updatePerson",ftpAttachment.getUpdatePerson());
        }
        if(StringUtils.hasText(ftpAttachment.getStatus())){
            jsonObj.put("status",ftpAttachment.getStatus());
        }
        return jsonObj;
    }
	
	@InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
        dateFormat.setLenient(true);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    } 
}
